package com.bawei.music.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.music.Mode;
import com.bawei.music.R;
import com.bawei.music.Song;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {
    private TextView tvCurrent;
    private SeekBar seekBar;
    private TextView tvDuration;
    private Button btStart;
    private Button btPre;
    private Button btNext;
    private Button btQuick;
    private Button btBack;
    private Button btRandom;
    private Button btLoop;
    private Button btOrder;
    //定时器：不断获取歌曲的当前进度更新UI
    private Timer mTimer = new Timer();
    private Handler mHandler = new Handler();

    //广播接收器
    private MusicRecevier mMusicRecevier;



    private MusicService.MusicBinder mMusicBinder;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MainActivity2.this,"绑定成功",Toast.LENGTH_LONG).show();
            mMusicBinder = (MusicService.MusicBinder) service;
            //！！！！！！！！必须绑定成功后设置数据！！！！！！！！！！！
            initSongs();//设置数据
            mMusicBinder.play();//默认播放第一首歌曲
            initTimer();//定时器
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService();//绑定服务
        inittRecevier();//注册广播
        initView();//findViewById
        initLisener();//点击事件


    }

    /**
     * 注册广播
     */
    private void inittRecevier() {
        mMusicRecevier = new MusicRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.music.next");
        intentFilter.addAction("com.bawei.music.pre");
        intentFilter.addAction("com.bawei.music.startOrPause");

        registerReceiver(mMusicRecevier,intentFilter);
    }

    /**
     * 定时器任务：每隔500毫秒获取歌曲的进度和总进度
     */
    private void initTimer() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //子线程不能直接更新UI，通过handler在主线程更新UI
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {//主线程
                        tvCurrent.setText(mMusicBinder.getCurrentTime());//当前时间
                        tvDuration.setText(mMusicBinder.getDurationTime());//总时间
                        seekBar.setProgress(mMusicBinder.getProgress());//进度条的进度

                    }
                });

            }
        },0,500);

    }


    private void initSongs() {
        List<Song> songs = new ArrayList<>();
        songs.add(new Song("再见","http://39.106.204.190:7777/mp3/36024806.mp3"));
        songs.add(new Song("句号","http://39.106.204.190:7777/mp3/1405283464.mp3"));
        songs.add(new Song("光年之外","http://39.106.204.190:7777/mp3/449818741.mp3"));
        songs.add(new Song("泡沫","http://39.106.204.190:7777/mp3/233931.mp3"));
        mMusicBinder.setList(songs);
    }
    //绑定服务
    private void bindService() {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);//onCreate->onStartCommand->onDestory
        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);//onCreate->onBind->onUnbind->onDestory
        //二合一：onCreate->onStartCommond->onbind->onunbind->onDestory
    }

    private void initLisener() {
        btStart.setOnClickListener(this);
        btPre.setOnClickListener(this);
        btNext.setOnClickListener(this);
        btQuick.setOnClickListener(this);
        btBack.setOnClickListener(this);
        btOrder.setOnClickListener(this);
        btRandom.setOnClickListener(this);
        btLoop.setOnClickListener(this);
        //拖拽进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {//进度条改变
                //progress 0-100
                if(fromUser){//来自用户的拖拽
                    mMusicBinder.seekTo(progress);
                    Log.d("ytx", "onProgressChanged: ");
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void initView() {
        tvCurrent = (TextView) findViewById(R.id.tv_current);
        seekBar = (SeekBar) findViewById(R.id.seek_bar);
        tvDuration = (TextView) findViewById(R.id.tv_duration);
        btStart = (Button) findViewById(R.id.bt_start);
        btPre = (Button) findViewById(R.id.bt_pre);
        btNext = (Button) findViewById(R.id.bt_next);
        btQuick = (Button) findViewById(R.id.bt_quick);
        btBack = (Button) findViewById(R.id.bt_back);
        btRandom = (Button) findViewById(R.id.bt_random);
        btLoop = (Button) findViewById(R.id.bt_loop);
        btOrder = (Button) findViewById(R.id.bt_order);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_start:
                mMusicBinder.startOrPause();
                break;
            case R.id.bt_pre:
                mMusicBinder.pre();
                break;
            case R.id.bt_next:
                mMusicBinder.next();
                break;
            case R.id.bt_quick:
                mMusicBinder.quick();
                break;
            case R.id.bt_back:
                mMusicBinder.back();
                break;
            case R.id.bt_loop:
                mMusicBinder.setMode(Mode.LOOP);
                break;
            case R.id.bt_random:
                mMusicBinder.setMode(Mode.RANDOM);
                break;
            case R.id.bt_order:
                mMusicBinder.setMode(Mode.ORDER);
                break;

        }
    }
    //页面销毁：解绑服务+释放媒体资源+取消定时器+解除注册广播
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);//解绑服务
        mMusicBinder.release();//释放媒体资源
        if (mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }//取消定时器
        unregisterReceiver(mMusicRecevier);//解除注册广播
    }

    //广播接受者：注册广播+接触注册
    class MusicRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.music.next".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.next();
            }else  if("com.bawei.music.pre".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.pre();
            }else if("com.bawei.music.startOrPause".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.startOrPause();
            }
        }
    }

}